package com.mkvld.appietijdenv2;

import com.mkvld.appietijdenv2.data.DayShifts;
import com.mkvld.appietijdenv2.data.Utils;
import com.mkvld.appietijdenv2.data.WeekShifts;
import com.mkvld.appietijdenv2.databases.ShiftDatabase;

import android.content.Context;
import android.content.Intent;
import android.widget.RemoteViews;
import android.widget.RemoteViewsService;

public class WidServiceV14 extends RemoteViewsService {

	@Override
	public RemoteViewsFactory onGetViewFactory(Intent intent) {
		return new WidSeviceFactoryV14(this.getApplicationContext(), intent);
	}

	static class WidSeviceFactoryV14 implements RemoteViewsService.RemoteViewsFactory {
		private static final int[] startIds = {
			R.id.wwl_day0_start, R.id.wwl_day1_start,
			R.id.wwl_day2_start, R.id.wwl_day3_start,
			R.id.wwl_day4_start, R.id.wwl_day5_start,
			R.id.wwl_day6_start
		};
		private static final int[] endIds = {
			R.id.wwl_day0_end, R.id.wwl_day1_end,
			R.id.wwl_day2_end, R.id.wwl_day3_end,
			R.id.wwl_day4_end, R.id.wwl_day5_end,
			R.id.wwl_day6_end
		};
		private Context context;
		ShiftDatabase db;

		public WidSeviceFactoryV14(Context context, Intent intent) { this.context = context; }
		
		@Override
		public void onCreate() { db = new ShiftDatabase(context); }

		@Override
		public int getCount() { return 3; }

		@Override
		public long getItemId(int position) { return position; }

		@Override
		public RemoteViews getLoadingView() { return null; }

		@Override
		public RemoteViews getViewAt(int position) {
			WeekShifts shifts = ShiftDatabase.db.getWeekShifts(Utils.getCurrentYear(), (Utils.getCurrentWeek() + position) % 52);
			RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.wid_week_layout);
			views.setTextViewText(R.id.wwl_title, context.getResources().getString(R.string.fs_week_title, (Utils.getCurrentWeek() + position) % 52 + 1) + (position == 0 ? context.getResources().getString(R.string.fs_current_week) : ""));
			for (int i = 0; i < 7; i++) {
				DayShifts dayShifts = shifts.getShifts()[i];
				if (dayShifts.size() == 0) {
					views.setTextViewText(startIds[i], "");
					views.setTextViewText(endIds[i], "");
				} else {
					views.setTextViewText(startIds[i], Utils.timeToString(dayShifts.getShifts().get(0).getStart()));
					views.setTextViewText(endIds[i], Utils.timeToString(dayShifts.getShifts().get(0).getEnd()));
				}
			}
			return views;
		}

		@Override
		public int getViewTypeCount() { return 1; }

		@Override
		public boolean hasStableIds() { return false; }

		

		@Override
		public void onDataSetChanged() { }

		@Override
		public void onDestroy() { }
		
	}
}
